package com.flashcash.solu.view.fragment.presenter;

import android.app.AlertDialog;

import com.flashcash.kotlin.data.LoanRange;
import com.flashcash.kotlin.data.LoaningAmoutBean;
import com.flashcash.kotlin.trace.TraceManager;
import com.flashcash.solu.R;
import com.flashcash.solu.bean.LatestLoanAppBean;
import com.flashcash.solu.bean.ResponseErrorBody;
import com.flashcash.solu.common.EventCollection;
import com.flashcash.solu.common.FieldParams;
import com.flashcash.solu.common.FieldParamsInt;
import com.flashcash.solu.common.TokenManager;
import com.flashcash.solu.harvester.collectin.Collector;
import com.flashcash.solu.harvester.collectin.PermissionUtil;
import com.flashcash.solu.view.MainActivity;
import com.flashcash.solu.view.camera.FaceDetectorPreImpl;
import com.flashcash.solu.view.fragment.LoanNormalView;
import com.flashcash.solu.widget.xleotoast.XLeoToast;
import com.google.gson.Gson;
import com.hwangjr.rxbus.RxBus;
import com.tbruyelle.rxpermissions.Permission;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.x.leo.apphelper.data.cache.CacheDataManage;

import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @作者:My
 * @创建日期: 2017/6/21 16:02
 * @描述:${TODO}
 * @更新者:${Author}$
 * @更新时间:${Date}$
 * @更新描述:${TODO}
 */

public class LoanNormalFraPreImp extends FaceDetectorPreImpl implements LoanNormalFraPresenter {


    private void requestPermissions(int permissionIndex) {
        if (dialog != null && dialog.isShowing()) {
            return;
        }

        if (permissionIndex >= PermissionUtil.neededPermissions.length) {

            this.qualificateLoan2();
            return;
        }

        String perm = PermissionUtil.neededPermissions[permissionIndex];

        if (!Collector.permissionGranted(perm, this.mView.getBaseActivity())) {
            new RxPermissions(this.mView.getBaseActivity())
                    .requestEach(perm)
                    .subscribe(new Subscriber<Permission>() {
                        @Override
                        public void onCompleted() {
                        }

                        @Override
                        public void onError(Throwable e) {
                        }

                        @Override
                        public void onNext(Permission permission) {

                            if (!permission.granted) {
                                showDialog(permission, permissionIndex);
                            } else {
                                requestPermissions(permissionIndex + 1);
                            }
                        }
                    });

        } else {
            requestPermissions(permissionIndex + 1);
        }
    }

    AlertDialog dialog;

    private void showDialog(Permission permission, int permissionIndex) {
        if (dialog != null) {
            dialog.dismiss();
        }

        dialog = new AlertDialog.Builder(this.mView.getBaseActivity())
                .setTitle("Attention")
                .setCancelable(false)
                .setPositiveButton("OK", (d, which) -> {

                    d.dismiss();
                    if (permission.shouldShowRequestPermissionRationale) {
                        requestPermissions(permissionIndex);

                    } else {
                        TraceManager.INSTANCE.toSettingPermissionActivity(this.mView.getBaseActivity(), PermissionUtil.neededPermissions[permissionIndex]);
                    }
                })
                .create();

        dialog.setMessage(this.mView.getBaseActivity().getString(R.string.need_permission_to_loan)
                + "\n\n" + PermissionUtil.getPermisinssionDesc(this.mView.getBaseActivity(), permissionIndex));


        if (!dialog.isShowing()) {
            dialog.show();
        }
    }

    @Override
    public void qualificateLoan() {
        this.requestPermissions(0);
    }

    //todo 跳转
    public void qualificateLoan2() {
        TokenManager instance = TokenManager.getInstance();

        if (!instance.hasLogin()) {//未登录
            TokenManager.isReSetLoanStatus = true;
            if (isAttached()) {
                ((LoanNormalView) mView).toReLogin();
            }
        } else {
            LatestLoanAppBean o = CacheDataManage.INSTANCE.obtainData(FieldParamsInt.LATESTBEAN, LatestLoanAppBean.class);

            if (o != null && FieldParams.LoanStatus.SUBMITTED.equals(o.getStatus())) {//已提交状态
                if (isAttached()) {
//                    ((LoanNormalView)mView).showFaceDetectorDialog();
                    RxBus.get().post(new EventCollection.GotoLoaning(null));//直接跳转到贷款详情页
//                    RxBus.get().post(new EventCollection.GotoLoaning(CacheDataManage.INSTANCE.obtainData(FieldParamsInt.TOTAL_AMOUNT, TotalAmount.class)));//直接跳转到贷款详情页
                }


            } else {//
                mUserApi.isQualification(TokenManager.getInstance().getToken())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<ResponseErrorBody>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {//显示需要多少天之后才能申请
                                Gson gson = new Gson();
                                if (e instanceof HttpException) {
                                    HttpException httpException = (HttpException) e;
                                    String errorBody = null;
                                    try {
                                        errorBody = httpException.response().errorBody().string();
                                        ResponseErrorBody responseErrorBody = gson.fromJson(errorBody, ResponseErrorBody.class);
                                        if (isAttached()) {
                                            ((LoanNormalView) mView).showErrorMessage("" + responseErrorBody.getMessage());
                                        }
                                    } catch (Exception e1) {
                                        e1.printStackTrace();
                                    }

                                } else {
                                    XLeoToast.showMessage(R.string.show_netwok_wrong);
                                }
                            }

                            @Override
                            public void onNext(ResponseErrorBody responseErrorBody) {
                                MainActivity.isSubmitVisible = true;
                                RxBus.get().post(CacheDataManage.INSTANCE.obtainData(FieldParamsInt.TO_LOAN_DATA, Object.class));
                            }
                        });
            }
        }
    }

    @Override
    public void requestDataSpan() {
        final LoanNormalView view = (LoanNormalView) mView;
        showLoading(null);
        mUserApi.getLoanRange()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(
                        new Subscriber<LoanRange>() {
                            @Override
                            public void onCompleted() {
                            }

                            @Override
                            public void onError(Throwable e) {
                                dismissLoading();
                                XLeoToast.showMessage(R.string.show_netwok_wrong);
                                view.onSpanObtainError();
                            }

                            @Override
                            public void onNext(LoanRange loanRange) {
                                if (loanRange == null) {
                                    onError(new IllegalArgumentException());
                                    return;
                                }
                                if (isAttached()) {
                                    dismissLoading();
                                    view.onSpanObtain(false, loanRange);
                                }
                            }
                        });
    }

    @Override
    public void getCurrentLoanResult(double currentMoney, double currentTerm, String periodUnit, long productId) {
        if (isAttached()) {
            showLoading("");
        }
        mUserApi.getLoanAmoutData(currentMoney, (int) currentTerm, periodUnit, productId)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<LoaningAmoutBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable throwable) {
                        if (isAttached()) {
                            dismissLoading();
                            XLeoToast.showMessage(R.string.network_error);
                        }
                    }

                    @Override
                    public void onNext(LoaningAmoutBean loaningAmoutBean) {
                        if (isAttached() && loaningAmoutBean != null && loaningAmoutBean.getDueAmount() != null) {
                            dismissLoading();
                            ((LoanNormalView) mView).updateTotalAmout(loaningAmoutBean);
                        } else {
                            onError(new IllegalStateException("amout bean error"));
                        }
                    }
                });
    }
}
